package com.cxb;

import java.util.List;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cxb.manager.WifiAdmin;
import com.cxb.manager.WifiApManager;
import com.cxb.manager.WifiHotConfigAdmin;
import com.cxb.utils.Debug;
import com.cxb.utils.WifiAPUtil;
import com.cxb.view.SwitchButton;
import com.cxb.view.SwitchButton.OnChangedListener;
import com.cxb.view.WifiItemView;
import com.cxb.view.WifiItemView.WIFI_ITEM_STATUS;

public class WifiActivity extends BaseActivity implements OnItemClickListener {

	private ListView lv_wifi_list;
	private WifiManager wifiManager;
	private WifiAdapter wifiAdapter;
	private TextView tvStatus, tv_wifitips;
	private SwitchButton wiperSwitch;
	private BroadcastReceiver receiverWifi;
	private Dialog dialog;
	private TextView tv_ssid;
	private EditText et_password;
	private ScanResult currentScanResult;
	private String password;
	private ScanResult connectedScanResult;
	private CheckBox cbShowPassword;
	private WifiItemView selectView;
	private WifiHotConfigAdmin wifiHotConfigAdmin;
	private WifiAdmin wifiAdmin;
	private WifiApManager wifiApManager;
	public enum WifiCipherType {
		WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wifi);
		wifiApManager=new WifiApManager(this);
		tvStatus = (TextView) findViewById(R.id.wifi_status);
		tv_ssid = (TextView) findViewById(R.id.tv_ssid);
		tv_wifitips = (TextView) findViewById(R.id.tv_wifitips);
		wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		wiperSwitch = (SwitchButton) findViewById(R.id.wiperSwitch);
		lv_wifi_list = (ListView) findViewById(R.id.lv_wifi_list);
		wifiAdapter = new WifiAdapter(this);
		lv_wifi_list.setAdapter(wifiAdapter);
		wiperSwitch.setChecked(wifiManager.isWifiEnabled());
		if (wifiManager.isWifiEnabled()) {
			scanWifi();
			
		}
		else
		{
			lv_wifi_list.setVisibility(View.GONE);
			tv_wifitips.setVisibility(View.VISIBLE);
		}
		wifiHotConfigAdmin = new WifiHotConfigAdmin(this);
		wiperSwitch.setOnChangedListener(new OnChangedListener() {

			@Override
			public void OnChanged(View wiperSwitch, boolean checkState) {
				if (checkState) {
					scanWifi();
				
				} else {
					closeWifi();
				
				}
			}
		});
		lv_wifi_list.setOnItemClickListener(this);
		View contentView = LayoutInflater.from(this).inflate(R.layout.wifi_connect_dialog, null);
		dialog = new Dialog(this, R.style.dialog);
		Window window = dialog.getWindow();
		LayoutParams p = window.getAttributes();
		p.width = LayoutParams.WRAP_CONTENT;
		p.width = LayoutParams.WRAP_CONTENT;
		window.setAttributes(p);
		dialog.setContentView(contentView);

		receiverWifi = new WifiReceiver();
		IntentFilter intentFilter = new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
		intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
		registerReceiver(receiverWifi, intentFilter);// 注册广播

		dialog.findViewById(R.id.tv_confirm).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
						connectWifi();
					}
				});
		dialog.findViewById(R.id.tv_cancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
		tv_ssid = (TextView) dialog.findViewById(R.id.tv_ssid);
		et_password = (EditText) dialog.findViewById(R.id.et_password);
		cbShowPassword = (CheckBox) dialog.findViewById(R.id.cb_show_password);
		cbShowPassword.setOnCheckedChangeListener(checkBox_Listener);

		wifiAdmin = new WifiAdmin(this);
	}

	private CheckBox.OnCheckedChangeListener checkBox_Listener = new CheckBox.OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (cbShowPassword.isChecked()) {
				// 文本正常显示
				et_password
						.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
				Editable etable = et_password.getText();
				Selection.setSelection(etable, etable.length());
			} else {
				// 文本以密码形式显示
				et_password.setInputType(InputType.TYPE_CLASS_TEXT
						| InputType.TYPE_TEXT_VARIATION_PASSWORD);
				// 下面两行代码实现: 输入框光标一直在输入文本后面
				Editable etable = et_password.getText();
				Selection.setSelection(etable, etable.length());
			}
		}
	};

	private void connectWifi() {
		// currentScanResult
		String password = et_password.getEditableText().toString();
		if (password.length() < 8) {
			Toast.makeText(this, R.string.input_right_wifi_password, 0).show();
		}
		this.password = password;
		if (currentScanResult != null) {

			boolean result = wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(
					currentScanResult.SSID, password,
					getWifiCipher(currentScanResult.capabilities)));
			// WifiConfiguration wifiConfiguration = createWifiConfig(
			// currentScanResult.SSID, password,
			// getWifiCipher(currentScanResult.capabilities));
			// boolean result = addNetWork(wifiConfiguration, this);
			if (result) {
				// wifiHotConfigAdmin.savePassword(currentScanResult.SSID,
				// password);
				// Toast.makeText(this, R.string.connect_wifi_success,
				// 0).show();
				if (selectView != null) {
					selectView.setStatus(WIFI_ITEM_STATUS.WIFI_CONNECTING);
				}
				// dialog.dismiss();
			} else {// 连接失败
				// Toast.makeText(this, R.string.connect_wifi_fail, 0).show();
				// dialog.dismiss();
			}
		}

	}

	private void showDialog(ScanResult scanResult) {
		currentScanResult = scanResult;
		tv_ssid.setText(scanResult.SSID);
		et_password.setText(wifiHotConfigAdmin
				.getSavedPassword(scanResult.SSID));
		dialog.show();
	}

	private void openWifi() {
		if (!wifiManager.isWifiEnabled()) {
			if(wifiApManager.isWifiApEnabled()){
				wifiApManager.closeWifiAp();
			}
			wifiManager.setWifiEnabled(true);
			lv_wifi_list.setVisibility(View.VISIBLE);
			tv_wifitips.setVisibility(View.GONE);
			
		}
	}

	private void closeWifi() {
		if (wifiManager.isWifiEnabled()) {
			tvStatus.setText(R.string.wlan_tip);
			wifiManager.setWifiEnabled(false);
			wifiAdapter.clearResult();
			wifiAdapter.notifyDataSetChanged();
			lv_wifi_list.setVisibility(View.GONE);
			tv_wifitips.setVisibility(View.VISIBLE);
		}
	}

	private void scanWifi() {

		tvStatus.setText(R.string.wlan_opening);
		openWifi();
		wifiManager.startScan();
		tvStatus.setText(R.string.wlan_searching);
	}

	public static WifiCipherType getWifiCipher(String capability) {

		String cipher = getEncryptString(capability);

		if (cipher.contains("WEP")) {

			return WifiCipherType.WIFICIPHER_WEP;
		} else if (cipher.contains("WPA") || cipher.contains("WPA2")
				|| cipher.contains("WPS")) {

			return WifiCipherType.WIFICIPHER_WPA;
		} else if (cipher.contains("unknow")) {

			return WifiCipherType.WIFICIPHER_INVALID;
		} else {
			return WifiCipherType.WIFICIPHER_NOPASS;
		}
	}

	public static String getEncryptString(String capability) {

		StringBuilder sb = new StringBuilder();

		if (TextUtils.isEmpty(capability))
			return "unknow";

		if (capability.contains("WEP")) {

			sb.append("WEP");

			return sb.toString();
		}

		if (capability.contains("WPA")) {

			sb.append("WPA");

		}
		if (capability.contains("WPA2")) {

			sb.append("/");

			sb.append("WPA2");

		}

		if (capability.contains("WPS")) {

			sb.append("/");

			sb.append("WPS");

		}

		if (TextUtils.isEmpty(sb))
			return "OPEN";

		return sb.toString();
	}

	@Override
	protected void onDestroy() {
		this.unregisterReceiver(receiverWifi);
		super.onDestroy();
	}

	SupplicantState lastConnectState;

	class WifiReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(
					WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {

				wifiAdapter.setData(wifiManager.getScanResults());
				wifiAdapter.notifyDataSetChanged();
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						if (wifiManager.isWifiEnabled()) {
							scanWifi();
						}
					}
				}, 5000);
				// Toast.makeText(context, "扫描完毕", Toast.LENGTH_LONG).show();

			} else if (intent.getAction().equals(
					WifiManager.WIFI_STATE_CHANGED_ACTION)) {// wifi状态

				int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
						WifiManager.WIFI_STATE_DISABLING);
				if (state == WifiManager.WIFI_STATE_ENABLED) {

					wiperSwitch.setChecked(true);
					scanWifi();
				} else {
					wiperSwitch.setChecked(false);
				}

			} else if (intent.getAction().equals(
					WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {// wifi状态

				SupplicantState state = intent
						.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);

				int errorState = intent.getIntExtra(
						WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
				Debug.printf("test", "SupplicantState state=" + state
						+ "  errorState=" + errorState + " lastConnectState="
						+ lastConnectState);
				if (currentScanResult != null) {
					if (state == SupplicantState.COMPLETED) {

						wifiHotConfigAdmin.savePassword(currentScanResult.SSID,
								password);
						// Toast.makeText(this, R.string.connect_wifi_success,
						// 0).show();
						Toast.makeText(WifiActivity.this,
								R.string.connect_wifi_success, 0).show();
						// dialog.dismiss();
						if (selectView != null && dialog != null
								&& !dialog.isShowing()) {
							selectView
									.setStatus(WIFI_ITEM_STATUS.WIFI_CONNECTED);
						}
					} else if (state == SupplicantState.DISCONNECTED) {// 连接失败
						if (lastConnectState == SupplicantState.FOUR_WAY_HANDSHAKE) {
							Toast.makeText(WifiActivity.this,
									R.string.connect_wifi_fail, 0).show();
						}
						// dialog.dismiss();
					} else if (state == SupplicantState.ASSOCIATING
							|| state == SupplicantState.ASSOCIATED
							|| state == SupplicantState.GROUP_HANDSHAKE) {
						if (selectView != null && dialog != null
								&& !dialog.isShowing()) {
							selectView
									.setStatus(WIFI_ITEM_STATUS.WIFI_CONNECTING);
						}
					}
					lastConnectState = state;
				}
			}

		}
	}

	class WifiAdapter extends BaseAdapter {
		private Context mContext;
		private List<ScanResult> scanResults;

		public WifiAdapter(Context context) {
			this.mContext = context;
		}

		public void clearResult() {
			if (scanResults != null) {
				scanResults.clear();
			}
		}

		public void setData(List<ScanResult> list) {
			this.scanResults = list;
		}

		@Override
		public int getCount() {

			if (scanResults == null) {
				return 0;
			}
			return scanResults.size();
		}

		@Override
		public Object getItem(int position) {

			return scanResults.get(position);
		}

		@Override
		public long getItemId(int position) {

			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			WifiItemView wifiItemView;
			if (convertView != null) {
				wifiItemView = (WifiItemView) convertView;
			} else {
				wifiItemView = new WifiItemView(WifiActivity.this);
			}
			// ScanResult scanResult = (ScanResult) getItem(position);
			wifiItemView.setWifiResult((ScanResult) getItem(position),
					wifiManager);

			return wifiItemView;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		ScanResult scanResult = (ScanResult) arg0.getAdapter()
				.getItem(position);
		WifiCipherType cipherType = getWifiCipher(scanResult.capabilities);
		if (cipherType == WifiCipherType.WIFICIPHER_NOPASS) {
			WifiItemView wifiItemView=(WifiItemView) arg1;
			wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(scanResult.SSID,
					password, cipherType));
			wifiItemView.setStatus(WIFI_ITEM_STATUS.WIFI_CONNECTING);
	
		} else {
			showDialog(scanResult);
		}

		selectView = (WifiItemView) arg1;
	}

}
